﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ClassLibraryMessageDataType;
using ClassLibraryMessageDispacher;

namespace GUI
{
  public  class ClassUI2MiddleCMDCollections
    {
        public void  DefaultSet(ref MiddleDevMessageDataType_Base o)
        {
            o.pHead = 0XF3;
        
            o.sq = GUICommunicationClass.instance.GetSquence();
        }
        private const byte HEAD = 0XF3;
        private const byte END = 0XF4;
        /// <summary>
        /// PC主动
        /// </summary>
        private const byte PC_ININATIVE = 0x00;
        /// <summary>
        /// 中位机主动
        /// </summary>
        private const byte MIDDLEINIVATIVE = 0x01;
        private static byte sumcheck(byte[] buf, int offest, int len)
        {
            byte b = 0;
            int num = 0;
            while (len-- > 0)
            {
                b = (byte)(b + buf[offest + num]);
                num++;
            }

            return b;
        }
        static  private void DefaultBytesCoverNeed2Sent(  ref byte[] aMarry)
        {

            byte z = aMarry[2];
            aMarry[2] = aMarry[3];
            aMarry[3] = z;
            z = aMarry[6];
            aMarry[6] = aMarry[7];
            aMarry[7] = z;

            aMarry[aMarry.Length - 2] = sumcheck(aMarry, 0, aMarry.Length - 2);
            aMarry[aMarry.Length - 1] = END;

        }
     /// <summary>
     /// 
     /// </summary>
     /// <param name="ip"></param>
     /// <param name="mesSend"></param>
     /// <param name="mesRecv"></param>
     /// <returns></returns>
        static private bool sendAndrecvMessage2MiddleDevs(ref MessagePackage mesSend, out MessagePackage mesRecv)
        {
            bool ret = GUICommunicationClass.instance.Sent2MiddleDevMessage(ref mesSend, out mesRecv);
            return ret;
        }
        /// <summary>
        /// 制作发送消息
        /// </summary>
        /// <param name="destIP"></param>
        /// <param name="strucobj"></param>
        /// <param name="squence"></param>
        /// <param name="mesRecv"></param>
        /// <exception cref="Exception"></exception>
        private static bool Creat2SentMessage(string destIP, object strucobj, ushort squence, out MessagePackage mesRecv)
        {      
            mesRecv = null;
            byte[] getbytes = StructByteConver.StructToBytes(strucobj);
            DefaultBytesCoverNeed2Sent(ref getbytes);
            ushort clen = (ushort)(getbytes[1 + 2 + 2+1] << 8 | getbytes[1 + 2 + 2+2] << 0);
            if (sumcheck(getbytes, 0, clen+1+1+2+2+2 ) != getbytes[getbytes.Length-2])
            {
                return false;
            }

            if (getbytes[1] != 0x00) { throw new Exception("direct err"); }
            ArraySegment<byte> buf1 = new ArraySegment<byte>(getbytes);
            SoureDetailInfo soinfo = new SoureDetailInfo();
            soinfo.sourepath = MessagePackagePath.UICom;
            DestDetailInfo deinfo = new DestDetailInfo();
            deinfo.destpath = MessagePackagePath.NetMiddleDeviceCom;
            deinfo.destIP = destIP;
            deinfo.DB = "";
            mesRecv = new MessagePackage(
                ProductType.request,
                PC_ININATIVE,
                squence,
                true,
                MessagePackagePath.UICom,
                MessagePackagePath.NetMiddleDeviceCom,
                soinfo,
                deinfo,
                "",
                buf1);
            return true;
        }
        /// <summary>
        /// 请求设备编号
        /// </summary>
        /// <param name="destIP"></param>
        /// <returns></returns>
        public static bool  GetDevCode(string destIP)
        {
            try
            {
                //===========1变化============用户自己构造对象

                MiddleDevMessageDataType_BaseRequestDevCode st = new MiddleDevMessageDataType_BaseRequestDevCode();

                //===========1变化============用户自己构造对象

                //============2固定填写==============
                st.pHead = HEAD;
                st.direct = PC_ININATIVE;
                st.sq = GUICommunicationClass.instance.GetSquence();
                ushort squence = st.sq;
                //===========2固定填写===============

                //===========3变化============用户自己填入字段

                st.mainCMD = 0X02;
                st.subCMD = 0X00;
                st.dataLen = 0X0001;
                st.data = new byte[1] { 0X02 };

                //===========3变化=================

                //===========4固定填写==============
                if (false == Creat2SentMessage(destIP, st, squence, out MessagePackage sentMes))
                {
                    throw new Exception("Creat2SentMessage check sum err!");
                }
                bool res= sendAndrecvMessage2MiddleDevs(ref sentMes, out MessagePackage outMes);
                //===========4固定填写==============

                if(res == true)
                {
                   // string strcmds = string.Format("main cmd {2x} sub cmd{2x:1}", st.mainCMD, st.subCMD);
                    Console.WriteLine("SUCCESS :  get current data Cmd sq :"+ outMes.squence.ToString()+" \r\n");
                }
                else
                {
                    Console.WriteLine("main cmd:" + st.mainCMD.ToString("2x") + "sub cmd:" + st.subCMD.ToString() +"time out\r\n");
                }
                return res;
               

            }
            catch (Exception e)
            {
                throw e;
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="destIP"></param>
        /// <param name="workStepsData"></param>
        /// <returns></returns>
        public static bool DownLoadWorkSteps(string destIP, ref byte[] workStepsData)
        {
            try
            {
               
                MiddleDevMessageDataType_WorkSteps st = new MiddleDevMessageDataType_WorkSteps();

                st.pHead = HEAD;
                st.direct = PC_ININATIVE;
                st.sq = GUICommunicationClass.instance.GetSquence();
                ushort squence = st.sq;
              
                st.mainCMD = 0X01;
                st.subCMD = 0X00;
                st.dataLen = 0X0015;
                st.data = workStepsData;
     
                string arry2str = ClassLibraryDevlopLib.ClassStr.Array2_HexStringsForma(ref workStepsData);
                ClassLibraryOverLog.ClassOverLogHelper.TraceAndRecordLogCommon(destIP +" sent work steps arry:" + arry2str);

                if ( false== Creat2SentMessage(destIP, st, squence, out MessagePackage sentMes))
                {
                    throw new Exception("Creat2SentMessage check sum err!");
                }
                bool res = sendAndrecvMessage2MiddleDevs(ref sentMes, out MessagePackage outMes);
               
                if (res == true)
                {
                    // string strcmds = string.Format("main cmd {2x} sub cmd{2x:1}", st.mainCMD, st.subCMD);
                    Console.WriteLine("SUCCESS :  get current data Cmd sq :" + outMes.squence.ToString() + " \r\n");
                }
                else
                {
                    Console.WriteLine("main cmd:" + st.mainCMD.ToString("2x") + "sub cmd:" + st.subCMD.ToString() + "time out\r\n");
                }
                return res;


            }
            catch (Exception e)
            {
                throw e;
            }
        }

        public static bool stopWorkSteps(string destIP,out MessagePackage outpack)
        {
            try
            {
                //===========1变化============用户自己构造对象

                MiddleDevMessageDataType_StopWorkSteps st = new MiddleDevMessageDataType_StopWorkSteps();

                //===========1变化============用户自己构造对象

                //============2固定填写==============
                st.pHead = HEAD;
                st.direct = PC_ININATIVE;
                st.sq = GUICommunicationClass.instance.GetSquence();
                ushort squence = st.sq;
                //===========2固定填写===============

                //===========3变化============用户自己填入字段

                st.mainCMD = 0X05;
                st.subCMD = 0X00;
                st.dataLen = 0X0015;
                st.data = new byte[21] { 0x03, 0x03, 0x00, 0x01, 0x10, 0x68, 0x03, 0xE8, 0x0a, 0x8c, 0x13, 0x88, 0x00, 0x14, 0x07, 0xd0, 0x27, 0x10, 0x00, 0x78, 0x00 };
            
                //===========3变化=================

                //===========4固定填写==============
                if (false == Creat2SentMessage(destIP, st, squence, out MessagePackage sentMes))
                {
                    throw new Exception("Creat2SentMessage check sum err!");
                }
                bool res = sendAndrecvMessage2MiddleDevs(ref sentMes, out MessagePackage outMes);
                //===========4固定填写==============
                outpack = outMes;

                if (res == true)
                {
                    // string strcmds = string.Format("main cmd {2x} sub cmd{2x:1}", st.mainCMD, st.subCMD);
                    Console.WriteLine("SUCCESS :  get current data Cmd sq :" + outMes.squence.ToString() + " \r\n");
                }
                else
                {
                    Console.WriteLine("main cmd:" + st.mainCMD.ToString("2x") + "sub cmd:" + st.subCMD.ToString() + "time out\r\n");
                }
                return res;


            }
            catch (Exception e)
            {
                throw e;
            }
        }


        //复位
        public static bool reset(string destIP, out MessagePackage outpack)
        {
            try
            {
                //===========1变化============用户自己构造对象

                MiddleDevMessageDataType_Reset st = new MiddleDevMessageDataType_Reset();

                //===========1变化============用户自己构造对象

                //============2固定填写==============
                st.pHead = HEAD;
                st.direct = PC_ININATIVE;
                st.sq = GUICommunicationClass.instance.GetSquence();
                ushort squence = st.sq;
                //===========2固定填写===============

                //===========3变化============用户自己填入字段

                st.mainCMD = 0X03;
                st.subCMD = 0X00;
                st.dataLen = 0X0000;


                //===========3变化=================

                //===========4固定填写==============
                if (false == Creat2SentMessage(destIP, st, squence, out MessagePackage sentMes))
                {
                    throw new Exception("Creat2SentMessage check sum err!");
                }
                bool res = sendAndrecvMessage2MiddleDevs(ref sentMes, out MessagePackage outMes);
                //===========4固定填写==============
                outpack = outMes;

                if (res == true)
                {
                    //string strcmds = string.Format("main cmd {2x} sub cmd{2x:1}", st.mainCMD, st.subCMD);
                    Console.WriteLine("SUCCESS :  get current data Cmd sq :" + outMes.squence.ToString() + " \r\n");
                }
                else
                {
                    Console.WriteLine("main cmd:" + st.mainCMD.ToString("2x") + "sub cmd:" + st.subCMD.ToString() + "time out\r\n");
                }

                return res;

            }
            catch (Exception e)
            {
                throw e;
            }
        }



    }
}
